/*
 * @lc app=leetcode.cn id=113 lang=cpp
 *
 * [113] 路径总和 II
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:

/*
    void preorder(vector<vector<int>> &res,TreeNode* root,int Sum,vector<int> row,int  targetSum)
    {
        if(root == NULL)
            return ;
        Sum += root->val;
        row.push_back(root->val);
        if(root->left == NULL && root->right == NULL)
        {
            if(Sum == targetSum)
                res.push_back(row);
        }
        else
        {
            preorder(res,root->left,Sum,row,targetSum);
            preorder(res,root->right,Sum,row,targetSum);
        }
    }

    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        vector<vector<int>> res;
        int Sum = 0;
        vector<int> row;
        preorder(res,root,Sum,row,targetSum);
        return res;
    }

    */


//**********************************方法二
    vector<vector<int>> res;
    vector<int> row;
    void dfs(TreeNode* root,int targetSum,int temp)
    {
        if(root == NULL)
            return;
        row.push_back(root->val);
        temp += root->val;
        if(temp == targetSum && root->left == NULL && root->right == NULL)
        {
            res.push_back(row);
            return;
        }
        if(root->left!=NULL)
        {
            dfs(root->left,targetSum,temp);
            row.pop_back();
        }
        if(root->right != NULL)
        {
            dfs(root->right,targetSum,temp);
            row.pop_back();
        }
    }

    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {

        if(root == NULL)
            return res;
        dfs(root,targetSum,0);
        return res;
    }
};
// @lc code=end

